package com.yao.mall.service.impl;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yao.mall.common.ErrorCode;
import com.yao.mall.config.AliPayConfig;
import com.yao.mall.config.BusinessException;
import com.yao.mall.mapper.ShoppingOrderDetailMapper;
import com.yao.mall.mapper.ShoppingOrderMapper;
import com.yao.mall.model.entity.ShoppingOrder;
import com.yao.mall.model.entity.ShoppingOrderDetail;
import com.yao.mall.service.PayService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiahua.yao
 * @version 1.0
 * @description 支付impl
 * @date 2024/4/9 15:22
 */
@Service
@Slf4j
public class PayServiceImpl implements PayService {

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE = "RSA2";
    @Resource
    private AliPayConfig aliPayConfig;

    @Resource
    private ShoppingOrderMapper shoppingOrderMapper;

    @Resource
    private ShoppingOrderDetailMapper shoppingOrderDetailMapper;

    @Override
    public String useAliPay(Long orderId) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        //订单信息
        if(orderId == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"支付订单信息错误");
        }
        ShoppingOrder shoppingOrder =shoppingOrderMapper.selectById(orderId);
        QueryWrapper<ShoppingOrderDetail> shoppingOrderDetailQueryWrapper = new QueryWrapper<>();
        shoppingOrderDetailQueryWrapper.eq("order_id",orderId);
        List<ShoppingOrderDetail> shoppingOrderDetails = shoppingOrderDetailMapper.selectList(shoppingOrderDetailQueryWrapper);
        StringBuilder goodsNames = new StringBuilder();
        for (ShoppingOrderDetail shoppingOrderDetail : shoppingOrderDetails) {
            String goodsName = shoppingOrderDetail.getGoodsName();
            if(goodsNames.indexOf(goodsName)<0){
                goodsNames.append(goodsName).append(';');
            }
        }
        //订单信息
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", shoppingOrder.getId());
        bizContent.set("total_amount", shoppingOrder.getTotalPrice());
        bizContent.set("subject", goodsNames);
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //支付结束重定向到支付订单状态更改接口
        alipayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
        alipayRequest.setReturnUrl("http://127.0.0.1:5173/paycallback");
        alipayRequest.setBizContent(bizContent.toString());
        try {
            //请求
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            log.info("*********************\n返回结果为：" + form);
            return form;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String payNotify(HttpServletRequest request){
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            log.info("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                log.info(name + " = " + request.getParameter(name));
            }
            String tradeNo = params.get("out_trade_no");

            String payTime = params.get("gmt_payment");
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime payDoneTime = LocalDateTime.parse(payTime, fmt);
            boolean checkSignature = false; // 验证签名
            try {
                checkSignature = AlipaySignature.rsaCheckV1(params,aliPayConfig.getAlipayPublicKey(),CHARSET,SIGN_TYPE);
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                log.info("交易名称: " + params.get("subject"));
                log.info("交易状态: " + params.get("trade_status"));
                log.info("支付宝交易凭证号: " + params.get("trade_no"));
                log.info("商户订单号: " + params.get("out_trade_no"));
                log.info("交易金额: " + params.get("total_amount"));
                log.info("买家在支付宝唯一id: " + params.get("buyer_id"));
                log.info("买家付款时间: " + params.get("gmt_payment"));
                log.info("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单为已支付
                ShoppingOrder shoppingOrder = new ShoppingOrder();
                shoppingOrder.setId(Long.parseLong(tradeNo));
                shoppingOrder.setOrderStatus(2); //已支付
                shoppingOrder.setPayTime(payDoneTime);
                shoppingOrderMapper.updateById(shoppingOrder);
            }
        }
        return "success";
    }
}
